package com.code.common.utils;



import com.code.modules.base.vo.TreeNodeVo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class ResTreeUtil {


    /**
     * list集合转tree
     * */
    public static List<TreeNodeVo> listTotree(List<TreeNodeVo> reslist) {

        List<Integer> plist = new ArrayList<Integer>();
        for(TreeNodeVo p : reslist) {
            plist.add(Integer.parseInt(String.valueOf(p.getPid())));
        }
        int root_point =  Collections.min(plist);

        //System.out.println("-root_point-"+root_point+"---plist---"+plist.toString());
        //System.out.println(reslist.toString());

        List<TreeNodeVo> restree = new ArrayList<TreeNodeVo>();

        for(TreeNodeVo r : reslist) {
            if(r.getPid() == root_point) {
                restree.add(r);
            }
            for(TreeNodeVo child : reslist) {
                if(child.getPid().intValue() == r.getId()) {
                    if(r.getChildren() == null) {
                        r.setChildren(new ArrayList<TreeNodeVo>());
                    }
                    r.getChildren().add(child);
                }
            }
        }

        //System.out.println(restree.toString());
        return restree;
    }







    /**
     * 方法二、
     * @param list
     * @return
     */
    public static List<TreeNodeVo> listToTree2(List<TreeNodeVo> list) {

        List<Integer> plist = new ArrayList<Integer>();
        for(TreeNodeVo p : list) {
            plist.add(Integer.parseInt(String.valueOf(p.getPid())));
        }
        int root_point =  Collections.min(plist);

        //用递归找子。
        List<TreeNodeVo> treeList = new ArrayList<TreeNodeVo>();
        for (TreeNodeVo tree : list) {
            if (tree.getPid() == root_point) {
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }



    private static TreeNodeVo findChildren(TreeNodeVo tree, List<TreeNodeVo> list) {
        for (TreeNodeVo node : list) {
            if (node.getPid().intValue() == tree.getId()) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<TreeNodeVo>());
                }
                tree.getChildren().add(findChildren(node, list));
            }
        }
        return tree;
    }






}
